package com.weixing.mall.provider.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.weixing.mall.base.constant.DatePattern;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.base.enums.WhetherEnum;
import com.weixing.mall.base.exception.BusinessException;
import com.weixing.mall.base.orm.MPage;
import com.weixing.mall.base.orm.PageUtil;
import com.weixing.mall.base.utils.EnumUtil;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.core.support.auth.AuthUtil;
import com.weixing.mall.core.support.auth.SysAuth;
import com.weixing.mall.core.utils.CommonUtil;
import com.weixing.mall.provider.api.model.dto.SaleAgentDto;
import com.weixing.mall.provider.api.model.enums.OrderTypeEnum;
import com.weixing.mall.provider.api.model.vo.AgentRpcVo;
import com.weixing.mall.provider.api.model.vo.KefuVo;
import com.weixing.mall.provider.api.model.vo.SysUserEditVo;
import com.weixing.mall.provider.api.service.AgentServiceRpc;
import com.weixing.mall.provider.api.service.SysConfigServiceFeign;
import com.weixing.mall.provider.api.service.SysUserRpcService;
import com.weixing.mall.provider.manager.AgentManager;
import com.weixing.mall.provider.manager.ProfitManager;
import com.weixing.mall.provider.mapper.AfterSaleMapper;
import com.weixing.mall.provider.mapper.OrderMapper;
import com.weixing.mall.provider.mapper.OrderOperationMapper;
import com.weixing.mall.provider.model.domain.Order;
import com.weixing.mall.provider.model.domain.OrderAgent;
import com.weixing.mall.provider.model.domain.OrderOperation;
import com.weixing.mall.provider.model.dto.ChgKefuRemarkDto;
import com.weixing.mall.provider.model.dto.OrderOperationDto;
import com.weixing.mall.provider.model.enums.*;
import com.weixing.mall.provider.model.query.AfterSaleQuery;
import com.weixing.mall.provider.model.query.AgentOrderQuery;
import com.weixing.mall.provider.model.query.CustomerOrderQuery;
import com.weixing.mall.provider.model.query.kefu.KefuOrderQuery;
import com.weixing.mall.provider.model.vo.FrontAgentOrderVo;
import com.weixing.mall.provider.model.vo.KefuAuditOrderVo;
import com.weixing.mall.provider.model.vo.SalesAchiVo;
import com.weixing.mall.provider.model.vo.StaticVo;
import com.weixing.mall.provider.model.vo.agent.AbnormalOrderStatisticVo;
import com.weixing.mall.provider.model.vo.agent.AgentSaleStatisticVo;
import com.weixing.mall.provider.model.vo.agent.UpPayReceiveVo;
import com.weixing.mall.provider.model.vo.agent.UpPayStatisticVo;
import com.weixing.mall.provider.service.*;
import com.weixing.mall.provider.util.AgentOrderUtil;
import com.weixing.mall.provider.util.OrderUtil;
import com.weixing.mall.util.number.NumberPatternEnum;
import com.weixing.mall.util.number.NumberToRmbUtil;
import jodd.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 订单模块-订单表 服务实现类
 * </p>
 *
 * @author Small
 * @since 2019-11-20
 */
@Service
public class KefuOrderServiceImpl implements IKefuOrderService {
    @Autowired
    private AgentServiceRpc agentServiceRpc;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderOperationMapper orderOperationMapper;
    @Autowired
    private IOrderAgentService orderAgentService;
    @Autowired
    private IAgentOrderService agentOrderService;
    @Autowired
    private SysUserRpcService sysUserRpcService;
    @Autowired
    private ProfitManager profitManager;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private SysConfigServiceFeign sysConfigService;
    @Autowired
    private IOrderOperationService orderOperationService;
    @Autowired
    private AgentManager agentManager;
    @Autowired
    private AfterSaleMapper afterSaleMapper;


    @Override
    public IPage selectOrderList(CustomerOrderQuery query, Page page) {
        SysAuth sysExt = AuthUtil.getSysExt();
        IPage<KefuAuditOrderVo> pageList = orderMapper.toAudit(page, query);
        //查询结果不为空
        List<KefuAuditOrderVo> records = pageList.getRecords();
        if (CollUtil.isNotEmpty(records)) {
            //循环set需要的值
            int i=1;
            for (KefuAuditOrderVo orderVo : records) {
                // 隐藏手机号.
                orderVo.setXu(i+"");
                i=i+1;
                if (ObjectUtil.isNotEmpty(sysExt)) {
                    orderVo.setContactPhone(sysExt.isSensitive() ? CommonUtil.coverMobile(orderVo.getContactPhone()) : orderVo.getContactPhone());
                }
                orderVo.setIsBind(StringUtil.isBlank(orderVo.getAgentCliamLine()) ? WhetherEnum.NO : WhetherEnum.YES);
                orderVo.setIsOnline(OrderFromEnum.MEMBER.equals(orderVo.getOrderFrom()) ? WhetherEnum.YES : WhetherEnum.NO);
                orderVo.setOrderSysTag(null == orderVo.getSysTag() ? "" : orderVo.getSysTag().getDesp());
                // 判断是否可删除
                if (OrderFromEnum.AGENT.equals(orderVo.getOrderFrom())
                        && OrderTypeEnum.NORMAL.equals(orderVo.getOrderType())
                        && OrderAuditStateEnum.AGENT_WAIT_AUDIT.equals(orderVo.getAuditStatus())) {
                    orderVo.setCanDel(1);
                }
                //操作时间
                OrderOperation orderOperation = orderOperationMapper.selectByOrderIdOperationTime(orderVo.getId());
                if (orderOperation != null) {
                    orderVo.setOperationTime(orderOperation.getCreatedTime());
                }

                //查询代理商 需收款、需上交款、待审核人、已审核人
                if (StringUtil.isNotBlank(orderVo.getAgentCliamLine())) {

                    String orderAuditorList = orderVo.getOrderAuditorList();
                    if (StringUtil.isNotBlank(orderAuditorList)) {
                        String[] split = orderAuditorList.split(",");
                        int length = split.length;
                        long unauditId = Long.parseLong(split[length - 1]);
                        Result<AgentRpcVo> rpcVoResult = agentServiceRpc.selectByAgentId(unauditId);
                        String auditeName = rpcVoResult.isSuccess() && rpcVoResult.getData() != null ? rpcVoResult.getData().getAgentName() : "";
                        orderVo.setAuditedName(auditeName);
                    }
                    if (AuditDeptEnum.AGENT.equals(orderVo.getAuditDept())) {
                        Result<AgentRpcVo> rpcResult = agentServiceRpc.selectByAgentId(orderVo.getAuditorId());
                        String unauditeName = rpcResult.isSuccess() && rpcResult.getData() != null ? rpcResult.getData().getAgentName() : "";
                        orderVo.setUnAuditor(unauditeName);
                    }

                    if (StringUtil.isNotBlank(orderVo.getAgentCliamLine())) {
                        QueryWrapper<OrderAgent> wrapper = new QueryWrapper<OrderAgent>().eq("order_id", orderVo.getId())
                                .eq("receivor_role", GlobalConstant.RECEIVORROLE_KEFU).eq("role_type", 2);
                        OrderAgent orderAgent = orderAgentService.getOne(wrapper);
                        if (null != orderAgent) {
                            orderVo.setPayAgentName(orderAgent.getAgentName());
                            orderVo.setPayPrice(orderAgent.getNeedUppay());
                        }
                    }
                }
            }
        }
        return pageList;
    }

    @Override
    public StaticVo selectOrderListTotal(CustomerOrderQuery query) {
        return orderMapper.toAuditTotalAmount(query);
    }

    @Override
    public IPage<KefuAuditOrderVo> toAudit(Page initMpPage, CustomerOrderQuery query) {
        SysAuth sysExt = AuthUtil.getSysExt();
        IPage<KefuAuditOrderVo> orderVoIPage = orderMapper.toAudit(initMpPage, query);

        // 是否需要计算需上交款

        List<KefuAuditOrderVo> records = orderVoIPage.getRecords();

        for (KefuAuditOrderVo record : records) {
            record.setIsOnline(OrderFromEnum.MEMBER.equals(record.getOrderFrom()) ? WhetherEnum.YES : WhetherEnum.NO);
            record.setIsBind(StringUtil.isBlank(record.getAgentCliamLine()) ? WhetherEnum.NO : WhetherEnum.YES);
            record.setContactPhone(sysExt.isSensitive() ? CommonUtil.coverMobile(record.getContactPhone()) : record.getContactPhone());
            //添加待审核人和未审核人  审核时间
            String orderAuditorList = record.getOrderAuditorList();
            if (StringUtil.isNotBlank(orderAuditorList)) {
                String[] split = orderAuditorList.split(",");
                int length = split.length;
                long unauditId = Long.parseLong(split[length - 1]);
                Result<AgentRpcVo> rpcVoResult = agentServiceRpc.selectByAgentId(unauditId);
                String auditeName = rpcVoResult.isSuccess() && rpcVoResult.getData() != null ? rpcVoResult.getData().getAgentName() : "";
                record.setAuditedName(auditeName);
            }
            if (AuditDeptEnum.AGENT.equals(record.getAuditDept())) {
                Result<AgentRpcVo> rpcResult = agentServiceRpc.selectByAgentId(record.getAuditorId());
                String unauditeName = rpcResult.isSuccess() && rpcResult.getData() != null ? rpcResult.getData().getAgentName() : "";
                record.setUnAuditor(unauditeName);
            }

            if (StringUtil.isNotBlank(record.getAgentCliamLine())) {
                QueryWrapper<OrderAgent> wrapper = new QueryWrapper<OrderAgent>().eq("order_id", record.getId())
                        .eq("receivor_role", GlobalConstant.RECEIVORROLE_KEFU).eq("role_type", 2);
                OrderAgent orderAgent = orderAgentService.getOne(wrapper);
                if (null != orderAgent) {
                    record.setPayAgentName(orderAgent.getAgentName());
                    record.setPayPrice(orderAgent.getNeedUppay());
                }
            }
        }
        return orderVoIPage;
    }

    @Override
    public StaticVo toAuditTotalAmount(CustomerOrderQuery query) {
        return orderMapper.toAuditTotalAmount(query);
    }

    @Override
    public IPage<KefuAuditOrderVo> noBindKefu(Page page, CustomerOrderQuery query) {
        SysAuth sysExt = AuthUtil.getSysExt();
        IPage<KefuAuditOrderVo> kefuAuditOrderVoIPage = orderMapper.noBindKefu(page, query);
        List<KefuAuditOrderVo> records = kefuAuditOrderVoIPage.getRecords();
        if (CollUtil.isNotEmpty(records)) {
            for (KefuAuditOrderVo record : records) {
                record.setContactPhone(sysExt.isSensitive() ? CommonUtil.coverMobile(record.getContactPhone()) : record.getContactPhone());
            }
        }
        return kefuAuditOrderVoIPage;
    }

    @Override
    public StaticVo noBindKefuTotalAmount(CustomerOrderQuery query) {
        return orderMapper.noBindKefuTotalAmount(query);
    }

    @Override
    public IPage<SalesAchiVo> salesOfAgent(Page initMpPage, OrderTypeEnum type, AgentOrderQuery query) {
        SysAuth sysExt = AuthUtil.getSysExt();
        long kefuId = sysExt.getUid();
        Result<MPage<AgentRpcVo>> result = agentServiceRpc.selectChildByKefuId(initMpPage.getCurrent(), initMpPage.getSize(), kefuId);
        if (!result.isSuccess()) {
            throw new BusinessException("代理商服务不可用");
        }
        IPage<AgentRpcVo> iPage = result.getData();
        ArrayList<SalesAchiVo> objects = Lists.newArrayList();
        MPage mPage = PageUtil.newPage(initMpPage.getCurrent(), initMpPage.getSize(), iPage.getTotal(), objects);
        if (null != iPage) {
            List<AgentRpcVo> records = iPage.getRecords();
            if (CollUtil.isNotEmpty(records)) {

                SalesAchiVo achiVo = null;
                for (AgentRpcVo agentVo : records) {
                    Long id = agentVo.getId();
                    query.setAgentId(id);
                    // 销售数量
                    StaticVo salesMap = agentOrderService.cntSalesOrder(type.getValue(), query);
                    long salesCnt = (long) salesMap.getTotalNum();
                    BigDecimal salesSum = salesMap.getTotalAmount();
                    // 断货数量
                    StaticVo outOfStockMap = agentOrderService.cntOutOfStockOrder(type.getValue(), query);
                    long outOfStockCnt = (long) outOfStockMap.getTotalNum();
                    BigDecimal outOfStockSum = outOfStockMap.getTotalAmount();
                    // 取消数量
                    StaticVo cancelMap = agentOrderService.cntCancelOrder(type.getValue(), query);
                    long cancelCnt = (long) cancelMap.getTotalNum();
                    BigDecimal cancelSum = cancelMap.getTotalAmount();
                    // 退货数量
                    StaticVo returnMap = agentOrderService.cntReturnOrder(type.getValue(), query);
                    long returnCnt = (long) returnMap.getTotalNum();
                    BigDecimal returnSum = returnMap.getTotalAmount();
                    // 实际销售数量
                    long realCnt = salesCnt - cancelCnt - returnCnt;
                    BigDecimal realSum = NumberUtil.sub(salesSum, cancelCnt, realCnt);
                    // 退货比
                    String returnRate = 0 == salesCnt ? "0.00%" : NumberUtil.formatPercent(NumberUtil.div(returnCnt, salesCnt, 2), 2);
                    achiVo = new SalesAchiVo();
                    achiVo.setName(agentVo.getAgentName());
                    achiVo.setSalesCnt(salesCnt);
                    achiVo.setSalesSum(NumberToRmbUtil.defaultFormat(salesSum));
                    achiVo.setOutOfStockCnt(outOfStockCnt);
                    achiVo.setOutOfStockSum(NumberToRmbUtil.defaultFormat(outOfStockSum));
                    achiVo.setCancelCnt(cancelCnt);
                    achiVo.setCancelSum(NumberToRmbUtil.defaultFormat(cancelSum));
                    achiVo.setReturnCnt(returnCnt);
                    achiVo.setReturnSum(NumberToRmbUtil.defaultFormat(returnSum));
                    achiVo.setRealCnt(realCnt);
                    achiVo.setRealSum(NumberToRmbUtil.defaultFormat(realSum));
                    achiVo.setReturnRate(returnRate);
                    objects.add(achiVo);
                }
            }
        }

        return mPage;
    }

    @Override
    public MPage<SalesAchiVo> salesOfKefu(Page initMpPage, OrderTypeEnum type, AgentOrderQuery query) {
        Result<MPage<KefuVo>> result = sysUserRpcService.selectKefuList(initMpPage.getCurrent(), initMpPage.getSize());
        if (!result.isSuccess()) {
            throw new BusinessException(result.getMsg());
        }
        IPage<KefuVo> iPage = result.getData();
        ArrayList<SalesAchiVo> objects = Lists.newArrayList();
        MPage mPage = PageUtil.newPage(initMpPage.getCurrent(), initMpPage.getSize(), iPage.getTotal(), objects);
        if (null != iPage) {
            List<KefuVo> records = iPage.getRecords();
            if (CollUtil.isNotEmpty(records)) {

                SalesAchiVo achiVo = null;
                for (KefuVo kefuVo : records) {
                    Long id = kefuVo.getId();
                    query.setCustomerId(id);
                    // 销售数量
                    StaticVo salesMap = agentOrderService.cntSalesOrder(type.getValue(), query);
                    long salesCnt = (long) salesMap.getTotalNum();
                    BigDecimal salesSum = salesMap.getTotalAmount();
                    // 断货数量
                    StaticVo outOfStockMap = agentOrderService.cntOutOfStockOrder(type.getValue(), query);
                    long outOfStockCnt = (long) outOfStockMap.getTotalNum();
                    BigDecimal outOfStockSum = outOfStockMap.getTotalAmount();
                    // 取消数量
                    StaticVo cancelMap = agentOrderService.cntCancelOrder(type.getValue(), query);
                    long cancelCnt = (long) cancelMap.getTotalNum();
                    BigDecimal cancelSum = cancelMap.getTotalAmount();
                    // 退货数量
                    StaticVo returnMap = agentOrderService.cntReturnOrder(type.getValue(), query);
                    long returnCnt = (long) returnMap.getTotalNum();
                    BigDecimal returnSum = returnMap.getTotalAmount();
                    // 实际销售数量
                    long realCnt = salesCnt - cancelCnt - returnCnt;
                    BigDecimal realSum = NumberUtil.sub(salesSum, cancelCnt, realCnt);
                    // 退货比
                    String returnRate = NumberUtil.formatPercent(NumberUtil.div(realCnt, salesCnt, 2), 2);
                    achiVo = new SalesAchiVo();
                    achiVo.setName(kefuVo.getRealName());
                    achiVo.setSalesCnt(salesCnt);
                    achiVo.setSalesSum(NumberToRmbUtil.defaultFormat(salesSum));
                    achiVo.setOutOfStockCnt(outOfStockCnt);
                    achiVo.setOutOfStockSum(NumberToRmbUtil.defaultFormat(outOfStockSum));
                    achiVo.setCancelCnt(cancelCnt);
                    achiVo.setCancelSum(NumberToRmbUtil.defaultFormat(cancelSum));
                    achiVo.setReturnCnt(returnCnt);
                    achiVo.setReturnSum(NumberToRmbUtil.defaultFormat(returnSum));
                    achiVo.setRealCnt(realCnt);
                    achiVo.setRealSum(NumberToRmbUtil.defaultFormat(realSum));
                    achiVo.setReturnRate(returnRate);
                    objects.add(achiVo);
                }
            }
        }

        return mPage;

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void bindBatch(String ids) {
        SysAuth sysExt = AuthUtil.getSysExt();
        String[] split = ids.split(",");
        List<Order> orderList = Lists.newArrayList();
        List<OrderAgent> orderAgentList = Lists.newArrayList();
        for (String id : split) {
            Order order = orderMapper.selectById(Long.parseLong(id));
            if (null == order) {
                throw new BusinessException(StrUtil.format("订单{}，不存在", order.getOrderSn()));
            }
            if (WhetherEnum.NO.getValue().equals(order.getIsPay())) {
                continue;
            }
            order.setAgentId(0L);
            order.setAgentSn("");
            order.setAgentName("");
            order.setAgentCliamLine("");
            order.setCustomerId(sysExt.getUid());
            order.setCustomerName(sysExt.getRealName());
            OrderUtil.clearOrderAgentClaim(order);
            // 订单审核直接流转到客服
            order.setAuditor(sysExt.getUid());
            order.setAuditDept(AuditDeptEnum.SERVICE_DEPT.getValue());
            order.setAuditStatus(OrderAuditStateEnum.AGENT_AUDIT_SUCCESS.getValue());
            order.setOrderStatus(OrderStateEnum.HAS_PAY.getValue());
            // 代理获利计算
            orderAgentList.addAll(profitManager.calcProfit(order, null, null));
            orderList.add(order);
        }
        orderService.executeSeckillOrderImport(orderList, orderAgentList);
    }

    @Override
    public void chgKefuRemark(ChgKefuRemarkDto dto, Long uid) {
        SysUserEditVo sysUserEditVo = sysConfigService.getUserById(uid).getData();
        orderMapper.updateCustomerRemark(dto);

        //客服操作记录
        OrderOperationDto orderOperationDto = new OrderOperationDto();
        //操作人类型为客服 2
        orderOperationDto.setOperatorType(OperateTypeEnum.EDIT);
        //操作人id
        orderOperationDto.setOperatorId(uid);
        if (sysUserEditVo != null) {
            //操作人
            orderOperationDto.setOperator(sysUserEditVo.getRealName());
        }
        //订单id
        orderOperationDto.setOrderId(dto.getId());
        //操作备注
        orderOperationDto.setRemark(dto.getRemark());
        //操作内容
        orderOperationDto.setOperation("客服只修改备注信息");
        orderOperationService.save(orderOperationDto);
    }

    @Override
    public IPage<KefuAuditOrderVo> selectKefuOrderList(Page initMpPage, CustomerOrderQuery query) {
        return orderMapper.selectKefuOrderList(initMpPage,query);
    }

    @Override
    public IPage<FrontAgentOrderVo> listOrderOfPage(Page page, AgentOrderQuery query) {
        if (null != query.getAgentId()){
            AgentRpcVo agentRpcVo = agentManager.loadAgentRpcVo(query.getAgentId());
            AgentOrderUtil.wripeQuery(query,agentRpcVo);
        }
        IPage<FrontAgentOrderVo> iPage = orderMapper.selectAgentOrderList(page, query);
        return iPage;
    }

    @Override
    public AgentSaleStatisticVo listOrderSalesStatistics(AgentOrderQuery query) {
        StaticVo todayAchi = null;
        StaticVo totalAchi = null;
        if (null != query.getAgentId()){
            AgentRpcVo agentRpcVo = agentManager.loadAgentRpcVo(query.getAgentId());
            AgentOrderUtil.wripeQuery(query,agentRpcVo);
        }
        todayAchi = orderMapper.agentAchievement(wrapSaleAchi(query, true));
        // 累计销售
        totalAchi = orderMapper.agentAchievement(wrapSaleAchi(query, false));
        AgentSaleStatisticVo vo = new AgentSaleStatisticVo();
        vo.setTodayAchi(null == todayAchi ? "0.00" : NumberToRmbUtil.format(todayAchi.getTotalAmount(), NumberPatternEnum.PAT_DEFAULT.getValue()));
        vo.setTodayAchiCnt(null == todayAchi ? 0 : todayAchi.getTotalNum());
        vo.setTotalAchi(null == totalAchi ? "0.00" : NumberToRmbUtil.format(totalAchi.getTotalAmount(), NumberPatternEnum.PAT_DEFAULT.getValue()));
        vo.setTotalAchiCnt(null == totalAchi ? 0 : totalAchi.getTotalNum());
        return vo;
    }

    @Override
    public IPage<FrontAgentOrderVo> selectAfterSaleOrderList(MPage page, AfterSaleQuery query) {
        IPage<FrontAgentOrderVo> iPage = afterSaleMapper.selectAfterSaleOrderList(page, query);
//        List<FrontAgentOrderVo> records = iPage.getRecords();
//        if (CollUtil.isNotEmpty(records)) {
//            for (FrontAgentOrderVo vo : records) {
//                OrderAgent orderAgent = orderAgentService.findByOrderIdAndAgentId(vo.getOrderId(), vo.getAgentId());
//                vo.setProfit(NumberToRmbUtil.format(orderAgent.getAgentProfit(), NumberPatternEnum.PAT_DEFAULT.getValue()));
//                if (AfterSalesTypeEnum.RETURN_GOODS.equals(query.getAfterSaleType())) {
//                    vo.setRefunder(orderAgent.getReceivor());
//                }
//            }
//        }
        return iPage;
    }

    @Override
    public AbnormalOrderStatisticVo selectAfterSaleStatistics(AfterSaleQuery query0) {
        String todayTimeFmt = DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN);
        // 今日断货总数
        AfterSaleQuery query = new AfterSaleQuery();
        BeanUtils.copyProperties(query0,query);
        query.setCheckStartTime(todayTimeFmt);
        query.setCheckEndTime(todayTimeFmt);
        StaticVo todayAchi = afterSaleMapper.countAndSumAfterSale(query);

        // 累计断货退货
        AfterSaleQuery query1 = new AfterSaleQuery();
        BeanUtils.copyProperties(query0,query1);
        StaticVo totalAchi = afterSaleMapper.countAndSumAfterSale(query1);
        // 累计销售
        AbnormalOrderStatisticVo vo = new AbnormalOrderStatisticVo();
        vo.setTodayAchi(todayAchi.getTotalAmount());
        vo.setTotalAchi(totalAchi.getTotalAmount());
        return vo;
    }

    @Override
    public AbnormalOrderStatisticVo outOfStockReportStatistics(AgentOrderQuery query0) {
        String todayTimeFmt = DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN);
        AgentOrderQuery queryCp = new AgentOrderQuery();
        BeanUtils.copyProperties(query0, queryCp);
        queryCp.setNosuppllyStartTime(todayTimeFmt);
        queryCp.setNosuppllyEndTime(todayTimeFmt);
        StaticVo todayAchi = orderMapper.agentAchievement(queryCp);
        // 累计断货退货
        // 累计销售
        AgentOrderQuery queryCp1 = new AgentOrderQuery();
        BeanUtils.copyProperties(query0, queryCp1);
        StaticVo totalAchi = orderMapper.agentAchievement(queryCp1);
        AbnormalOrderStatisticVo vo = new AbnormalOrderStatisticVo();
        vo.setTotalAchi(totalAchi.getTotalAmount());
        vo.setTodayAchi(todayAchi.getTotalAmount());
        return vo;
    }

    @Override
    public AbnormalOrderStatisticVo canceledStatistics(AgentOrderQuery query0) {
        String todayTimeFmt = DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN);
        // 今日取消数量
        AgentOrderQuery queryCp = new AgentOrderQuery();
        BeanUtils.copyProperties(query0, queryCp);
        queryCp.setNosuppllyStartTime(todayTimeFmt);
        queryCp.setNosuppllyEndTime(todayTimeFmt);
        StaticVo todayResult = orderMapper.agentAchievement(queryCp);

        // 累计取消数量
        AgentOrderQuery queryCp1 = new AgentOrderQuery();
        BeanUtils.copyProperties(query0, queryCp1);
        StaticVo totalResult = orderMapper.agentAchievement(queryCp1);

        AbnormalOrderStatisticVo vo = new AbnormalOrderStatisticVo();
        vo.setTodayAchi(todayResult.getTotalAmount());
        vo.setTotalAchi(totalResult.getTotalAmount());
        return vo;
    }

    @Override
    public IPage<FrontAgentOrderVo> selectUpPayOrderList(Page page, AgentOrderQuery query) {
        IPage<FrontAgentOrderVo> iPage = orderMapper.selectUpPayOrderList(page, query);
        List<FrontAgentOrderVo> records = iPage.getRecords();
        if (CollUtil.isNotEmpty(records)) {
            for (FrontAgentOrderVo vo : records) {
                    OrderAgent orderAgent = orderAgentService.findKefuReceive(vo.getOrderId(), query.getAuditor());
                    if (null != orderAgent) {
                        vo.setNeedReceive(NumberToRmbUtil.format(orderAgent.getNeedReceive(), NumberPatternEnum.PAT_DEFAULT.getValue()));
                        vo.setPayer(orderAgent.getPayer());
                        vo.setReceivor(orderAgent.getReceivor());
                    }
            }
        }
        return iPage;
    }

    @Override
    public UpPayStatisticVo upPayStatistics(AgentOrderQuery query) {
        // 已收款
        BigDecimal hasUpPay = orderAgentService.sumKefuUpPayStatistics(query,GlobalConstant.PROFIT_SETTLE_STATE_HASUP);
        UpPayStatisticVo vo = new UpPayStatisticVo();
        vo.setNeedUppay(NumberToRmbUtil.format(hasUpPay, NumberPatternEnum.PAT_DEFAULT.getValue()));
        vo.setHasUpPay(NumberToRmbUtil.format(hasUpPay, NumberPatternEnum.PAT_DEFAULT.getValue()));
        return vo;
    }

    @Override
    public IPage<SalesAchiVo> achievement(Page page, OrderTypeEnum type, AgentOrderQuery query) {
        SaleAgentDto saleAgentDto = new SaleAgentDto();
        saleAgentDto.setCustomerId(query.getCustomerId());
        saleAgentDto.setCurrentPage(page.getCurrent());
        saleAgentDto.setPageSize(page.getSize());
        saleAgentDto.setAgentId(query.getSelectedAgentId());
        saleAgentDto.setAgentName(query.getAgentName());
        Result<MPage<AgentRpcVo>> result = agentServiceRpc.selectChildByAgent(saleAgentDto);
        if (!result.isSuccess()) {
            throw new BusinessException("代理商服务不可用");
        }
        IPage<AgentRpcVo> iPage = result.getData();
        ArrayList<SalesAchiVo> objects = Lists.newArrayList();

        if (null != iPage) {
            List<AgentRpcVo> records = iPage.getRecords();
            if (CollUtil.isNotEmpty(records)) {
                SalesAchiVo achiVo = null;
                for (AgentRpcVo agentVo : records) {
                    // 销售数量
                    StaticVo salesMap = cntSalesOrder(type.getValue(), query, agentVo);
                    long salesCnt = (long) salesMap.getTotalNum();
                    BigDecimal salesSum = salesMap.getTotalAmount();
//                    // 断货数量
                    StaticVo outOfStockMap = cntOutOfStockOrder(type.getValue(), query, agentVo);
                    long outOfStockCnt = (long) outOfStockMap.getTotalNum();
                    BigDecimal outOfStockSum = outOfStockMap.getTotalAmount();
                    // 取消数量
                    StaticVo cancelMap = cntCancelOrder(type.getValue(), query, agentVo);
                    long cancelCnt = (long) cancelMap.getTotalNum();
                    BigDecimal cancelSum = cancelMap.getTotalAmount();
                    // 退货数量
                    StaticVo returnMap = cntReturnOrder(type.getValue(), query, agentVo);
                    long returnCnt = (long) returnMap.getTotalNum();
                    BigDecimal returnSum = returnMap.getTotalAmount();
                    // 实际销售数量
                    long realCnt = salesCnt - cancelCnt - returnCnt;
                    BigDecimal realSum = NumberUtil.sub(salesSum, cancelSum, returnSum);
                    // 退货比
                    String returnRate = 0 == salesCnt ? "0.00%" : NumberUtil.formatPercent(NumberUtil.div(returnCnt, salesCnt, 2), 2);
                    achiVo = new SalesAchiVo();
                    achiVo.setName(agentVo.getAgentName());
                    achiVo.setSalesCnt(salesCnt);
                    achiVo.setSalesSum(NumberToRmbUtil.defaultFormat(salesSum));
                    achiVo.setOutOfStockCnt(outOfStockCnt);
                    achiVo.setOutOfStockSum(NumberToRmbUtil.defaultFormat(outOfStockSum));
                    achiVo.setCancelCnt(cancelCnt);
                    achiVo.setCancelSum(NumberToRmbUtil.defaultFormat(cancelSum));
                    achiVo.setReturnCnt(returnCnt);
                    achiVo.setReturnSum(NumberToRmbUtil.defaultFormat(returnSum));
                    achiVo.setRealCnt(realCnt);
                    achiVo.setRealSum(NumberToRmbUtil.defaultFormat(realSum));
                    achiVo.setReturnRate(returnRate);
                    objects.add(achiVo);
                }
            }
        }
        MPage mPage = PageUtil.newPage(page.getCurrent(), page.getSize(), iPage.getTotal(), objects);
        return mPage;
    }

    private StaticVo cntSalesOrder(int orderType, AgentOrderQuery query, AgentRpcVo agentVo) {
        AgentOrderQuery queryCp = new AgentOrderQuery();
        BeanUtils.copyProperties(query, queryCp);
        queryCp.setOrderType(EnumUtil.getIEnum(OrderTypeEnum.class, orderType));
        queryCp.setAuditStartTime(query.getStartTime());
        queryCp.setAuditEndTime(query.getEndTime());
        queryCp.setStartTime(null);
        queryCp.setEndTime(null);
        AgentOrderUtil.wripeQuery(queryCp, agentVo);

        return orderMapper.agentAchievement(queryCp);
    }

    private StaticVo cntOutOfStockOrder(int orderType, AgentOrderQuery query, AgentRpcVo agentRpcVo) {
        AgentOrderQuery queryCp = new AgentOrderQuery();
        BeanUtils.copyProperties(query, queryCp);
        queryCp.setOrderType(EnumUtil.getIEnum(OrderTypeEnum.class, orderType));
        queryCp.setItemStatus(ProductStatusEnum.STATUS6.getValue());
        queryCp.setNosuppllyStartTime(query.getStartTime());
        queryCp.setNosuppllyEndTime(query.getEndTime());
        queryCp.setStartTime(null);
        queryCp.setEndTime(null);
        AgentOrderUtil.wripeQuery(queryCp, agentRpcVo);

        return orderMapper.agentAchievement(queryCp);
    }

    private StaticVo cntCancelOrder(int orderType, AgentOrderQuery query, AgentRpcVo agentRpcVo) {

        AgentOrderQuery queryCp = new AgentOrderQuery();
        BeanUtils.copyProperties(query, queryCp);
        queryCp.setOrderType(EnumUtil.getIEnum(OrderTypeEnum.class, orderType));
        queryCp.setItemStatus(ProductStatusEnum.STATUS7.getValue());
        queryCp.setNosuppllyStartTime(query.getStartTime());
        queryCp.setNosuppllyEndTime(query.getEndTime());
        queryCp.setStartTime(null);
        queryCp.setEndTime(null);
        AgentOrderUtil.wripeQuery(queryCp, agentRpcVo);

        return orderMapper.agentAchievement(queryCp);
    }


    private StaticVo cntReturnOrder(int orderType, AgentOrderQuery query, AgentRpcVo agentRpcVo) {
        AfterSaleQuery qs = new AfterSaleQuery();
        qs.setAgentId(query.getAgentId());
        qs.setAfterSaleType(AfterSalesTypeEnum.RETURN_GOODS);
        qs.setOrderType(query.getOrderType());
        qs.setCheckStartTime(query.getStartTime());
        qs.setCheckEndTime(query.getEndTime());
        AgentOrderUtil.wripeQuery(qs, agentRpcVo);
        StaticVo todayAchi = afterSaleMapper.countAndSumAfterSale(qs);
        return todayAchi;
    }



    private AgentOrderQuery wrapSaleAchi(AgentOrderQuery query,boolean isToday) {
        AgentOrderQuery tq = new AgentOrderQuery();
        BeanUtils.copyProperties(query, tq);
        if (isToday){
            String todayTimeFmt = DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN);
            tq.setAuditStartTime(todayTimeFmt);
            tq.setAuditEndTime(todayTimeFmt);
        }

        return tq;
    }

}
